import NProgress from 'nprogress' // progress bar
import type { LocationQueryRaw, Router } from 'vue-router'

import { useUserStore } from '@/store'
import { isLogin } from '@/utils/auth'
import { WHITE_LIST } from '../constants'

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const WHITE_LIST_NAME = WHITE_LIST.map( (item,index) => {
      return item.name
    })
    if (WHITE_LIST_NAME.includes(<string>to.name)){
      next()
      NProgress.done()
      return
    }

    const userStore = useUserStore()
    if (isLogin()) {
      if (Array.isArray(userStore.role) && userStore.role.length > 0) {
        next()
      } else {
        try {
          await userStore.info()
          next()
        } catch (error) {
          await userStore.logout()
          next({ name: 'login', query: { redirect: to.name, ...to.query} as LocationQueryRaw})
        }
      }
    } else {
      if (to.name === 'login') {
        next()
        NProgress.done()
        return
      }
      next({ name: 'login', query: { redirect: to.name, ...to.query } as LocationQueryRaw})
    }
  })
}
